package com.lej.core.widget.customview

import android.content.Context
import android.graphics.Color
import android.graphics.Rect
import android.view.MotionEvent
import android.view.View
import android.view.ViewConfiguration
import android.view.ViewGroup
import androidx.constraintlayout.widget.ConstraintLayout
import com.lej.core.dsl.layout_id
import com.lej.core.dsl.match_parent
import com.lej.core.utils.build
import com.lej.core.utils.createBitmapFromViewTransparent
import com.lej.core.utils.showInQueue
import com.lxj.xpopup.core.BasePopupView
import com.lxj.xpopup.enums.PopupAnimation
import com.lxj.xpopup.impl.FullScreenPopupView
import com.lxj.xpopup.interfaces.SimpleCallback
import com.qmuiteam.qmui.kotlin.onClick
import com.qmuiteam.qmui.util.QMUIDrawableHelper
import com.qmuiteam.qmui.widget.QMUIRadiusImageView2

object PopupsHelper {
    /**
     * 依据view弹出蒙层遮盖弹窗
     * @param radius 图层圆角显示
     * @param isOval 是否为圆形图片
     */
    fun View.showTips(
        radius: Int = 0,
        stokeWidth: Int = 0,
        onDismiss: () -> Unit = {},
        contentClick: (() -> Unit)? = null,
        targetViewTransparent: Boolean = true,
        targetViewHide: Boolean = false,//是否隐藏目标view
        block: ViewGroup.(location: IntArray, targetIdStr: String) -> Unit = { _, _ -> }
    ) {
        post {
            val size = IntArray(2).also { getLocationOnScreen(it) }
            val viewLp = ConstraintLayout.LayoutParams(width, height).apply {
                leftMargin = size[0]
                topMargin = size[1]
                leftToLeft = ConstraintLayout.LayoutParams.PARENT_ID
                topToTop = ConstraintLayout.LayoutParams.PARENT_ID
            }
            val cutBitmap = if (targetViewTransparent) createBitmapFromViewTransparent(this) else QMUIDrawableHelper.createBitmapFromView(this)
            val imageIdStr = "image"
            QMUITipsFullScreenPopup(context, block = { pop ->
                addView(QMUIRadiusImageView2(context).apply {
                    layout_id = imageIdStr
                    if (!targetViewHide) {
                        setImageBitmap(cutBitmap)
                    }
                    cornerRadius = radius
                    if (stokeWidth > 0) {
                        this.borderWidth = stokeWidth
                        borderColor = Color.WHITE
                    }
                    if (contentClick != null) {
                        setOnClickListener {
                            contentClick()
                            pop.dismiss()
                        }
                    }
                }, viewLp)
                block(size, imageIdStr)
            }).build(isDismissOnTouchOutside = true, isClickThrough = true, popupAnimation = PopupAnimation.NoAnimation, xPopupCallback = object : SimpleCallback() {
                override fun onDismiss(popupView: BasePopupView?) {
                    onDismiss()
                }
            })
                .show()
        }
    }

    fun showTips(
        parent: View,
        showInQueue: Boolean = false,
        onDismiss: () -> Unit = {},
        contentClick: (() -> Unit)? = null,
        block: ViewGroup.(BasePopupView) -> Unit = { }
    ) {
        QMUITipsFullScreenPopup(parent.context, block = block, contentClick = contentClick)
            .apply { clipChildren = false }
            .build(isDismissOnTouchOutside = true, isClickThrough = true, popupAnimation = PopupAnimation.NoAnimation, xPopupCallback = object : SimpleCallback() {
                override fun onDismiss(popupView: BasePopupView?) {
                    onDismiss()
                }
            }).apply {
                if (showInQueue) showInQueue()
                else show()
            }
    }

    class QMUITipsFullScreenPopup(
        context: Context,
        val block: ViewGroup.(BasePopupView) -> Unit = { },
        val contentClick: (() -> Unit)? = null
    ) : FullScreenPopupView(context) {
        override fun initPopupContent() {
            super.initPopupContent()
            popupInfo.hasShadowBg = true
        }

        override fun onCreate() {
            super.onCreate()
            (contentView as? ViewGroup)?.block(this)
            (popupImplView as? ViewGroup)?.onClick { contentClick?.invoke() ?: dismiss() }
        }

        private var oX = 0f
        private var oY: Float = 0f
        val touchSlop = ViewConfiguration.get(context).getScaledTouchSlop()
        override fun onTouchEvent(event: MotionEvent?): Boolean {
            // 如果自己接触到了点击，并且不在PopupContentView范围内点击，则进行判断是否是点击事件,如果是，则dismiss
            val rect = Rect()
            popupContentView.getGlobalVisibleRect(rect)
            when (event!!.action) {
                MotionEvent.ACTION_DOWN -> {
                    oX = event.x
                    oY = event.y
                }
                MotionEvent.ACTION_UP -> {
                    val dx = event.x - oX
                    val dy = event.y - oY
                    val distance = Math.sqrt(Math.pow(dx.toDouble(), 2.0) + Math.pow(dy.toDouble(), 2.0)).toFloat()
                    if (distance < touchSlop && popupInfo.isDismissOnTouchOutside) {
                        dismiss()
                    }
                    oX = 0f
                    oY = 0f
                }
            }
            if (dialog != null && popupInfo.isClickThrough) dialog.passClick(event)
            return true
        }

        override fun addInnerContent() {
            contentView = ConstraintLayout(context)
            val params = ViewGroup.LayoutParams(match_parent, match_parent)
            centerPopupContainer.addView(contentView, params)
        }

    }
}